package com.ohos.liveeventbus.utils;

import com.ohos.liveeventbus.ipc.annotation.SuppressLint;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilityLifecycleCallbacks;
import ohos.aafwk.ability.AbilityPackage;
import ohos.aafwk.ability.RunningProcessInfo;
import ohos.app.Context;
import ohos.app.IAbilityManager;
import ohos.utils.PacMap;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * from Github: https://github.com/Blankj/AndroidUtilCode
 * thanks Blankj
 */
public final class AppUtils {

    private static final String PERMISSION_ACTIVITY_CLASS_NAME =
            "com.blankj.utilcode.util.PermissionUtils$PermissionActivity";

    private static final ActivityLifecycleImpl ACTIVITY_LIFECYCLE = new ActivityLifecycleImpl();

    @SuppressLint("StaticFieldLeak")
    private static AbilityPackage sApplication;

    private AppUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * Init utils.
     * <p>Init it in the class of Application.</p>
     *
     * @param context context
     */
    public static void init(final Context context) {
        if (context == null) {
            init(getApplicationByReflect());
            return;
        }
        init((AbilityPackage) context);
    }

    /**
     * Init utils.
     * <p>Init it in the class of Application.</p>
     *
     * @param app application
     */
    public static void init(final AbilityPackage app) {
        if (sApplication == null) {
            if (app == null) {
                sApplication = getApplicationByReflect();
            } else {
                sApplication = app;
            }
            sApplication.registerCallbacks(ACTIVITY_LIFECYCLE, null);
        } else {
            if (app != null && app.getClass() != sApplication.getClass()) {
                sApplication.unregisterCallbacks(ACTIVITY_LIFECYCLE, null);
                ACTIVITY_LIFECYCLE.mActivityList.clear();
                sApplication = app;
                sApplication.registerCallbacks(ACTIVITY_LIFECYCLE, null);
            }
        }
    }

    /**
     * Return the context of Application object.
     *
     * @return the context of Application object
     */
    public static AbilityPackage getApp() {
        if (sApplication != null) return sApplication;
        AbilityPackage app = getApplicationByReflect();
        init(app);
        return app;
    }

    private static AbilityPackage getApplicationByReflect() {
        try {
            Class<?> className = Class.forName("com.ohos.liveeventbus.core.BaseApplication");
            Object instance = className.newInstance();
            Object app = className.getMethod("get").invoke(instance);
            return (AbilityPackage) app;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new NullPointerException("u should init first");
    }

    static ActivityLifecycleImpl getActivityLifecycle() {
        return ACTIVITY_LIFECYCLE;
    }

    static LinkedList<Ability> getActivityList() {
        return ACTIVITY_LIFECYCLE.mActivityList;
    }

    static Context getTopActivityOrApp() {
        if (isAppForeground()) {
            Ability topActivity = ACTIVITY_LIFECYCLE.getTopActivity();
            return topActivity == null ? AppUtils.getApp() : topActivity;
        } else {
            return AppUtils.getApp();
        }
    }

    static boolean isAppForeground() {
        IAbilityManager am = AppUtils.getApp().getAbilityManager();
        if (am == null) return false;
        List<RunningProcessInfo> info = am.getAllRunningProcesses();
        if (info == null || info.size() == 0) return false;
        for (RunningProcessInfo aInfo : info) {
            if (aInfo.getWeight() == RunningProcessInfo.WEIGHT_FOREGROUND) {
                return aInfo.getProcessName().equals(AppUtils.getApp().getBundleName());
            }
        }
        return false;
    }

    static class ActivityLifecycleImpl implements AbilityLifecycleCallbacks {

        final LinkedList<Ability> mActivityList = new LinkedList<>();
        final Map<Object, OnAppStatusChangedListener> mStatusListenerMap = new HashMap<>();
        final Map<Ability, Set<OnActivityDestroyedListener>> mDestroyedListenerMap = new HashMap<>();

        private int mForegroundCount = 0;
        private int mConfigCount = 0;
        private boolean mIsBackground = false;

        Ability getTopActivity() {
            if (!mActivityList.isEmpty()) {
                final Ability topActivity = mActivityList.getLast();
                if (topActivity != null) {
                    return topActivity;
                }
            }
            Ability topActivityByReflect = getTopActivityByReflect();
            if (topActivityByReflect != null) {
                setTopActivity(topActivityByReflect);
            }
            return topActivityByReflect;
        }

        void addOnAppStatusChangedListener(final Object object,
                                           final OnAppStatusChangedListener listener) {
            mStatusListenerMap.put(object, listener);
        }

        void removeOnAppStatusChangedListener(final Object object) {
            mStatusListenerMap.remove(object);
        }

        void removeOnActivityDestroyedListener(final Ability activity) {
            if (activity == null) return;
            mDestroyedListenerMap.remove(activity);
        }

        void addOnActivityDestroyedListener(final Ability activity,
                                            final OnActivityDestroyedListener listener) {
            if (activity == null || listener == null) return;
            Set<OnActivityDestroyedListener> listeners;
            if (!mDestroyedListenerMap.containsKey(activity)) {
                listeners = new HashSet<>();
                mDestroyedListenerMap.put(activity, listeners);
            } else {
                listeners = mDestroyedListenerMap.get(activity);
                if (listeners.contains(listener)) return;
            }
            listeners.add(listener);
        }

        private void postStatus(final boolean isForeground) {
            if (mStatusListenerMap.isEmpty()) return;
            for (OnAppStatusChangedListener onAppStatusChangedListener : mStatusListenerMap.values()) {
                if (onAppStatusChangedListener == null) return;
                if (isForeground) {
                    onAppStatusChangedListener.onForeground();
                } else {
                    onAppStatusChangedListener.onBackground();
                }
            }
        }

        private void setTopActivity(final Ability activity) {
            if (PERMISSION_ACTIVITY_CLASS_NAME.equals(activity.getClass().getName())) return;
            if (mActivityList.contains(activity)) {
                if (!mActivityList.getLast().equals(activity)) {
                    mActivityList.remove(activity);
                    mActivityList.addLast(activity);
                }
            } else {
                mActivityList.addLast(activity);
            }
        }

        private void consumeOnActivityDestroyedListener(Ability activity) {
            Iterator<Map.Entry<Ability, Set<OnActivityDestroyedListener>>> iterator
                    = mDestroyedListenerMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Ability, Set<OnActivityDestroyedListener>> entry = iterator.next();
                if (entry.getKey() == activity) {
                    Set<OnActivityDestroyedListener> value = entry.getValue();
                    for (OnActivityDestroyedListener listener : value) {
                        listener.onActivityDestroyed(activity);
                    }
                    iterator.remove();
                }
            }
        }

        private Ability getTopActivityByReflect() {
            return null;
        }

        private static void fixSoftInputLeaks(final Ability activity) {
            if (activity == null) return;
        }

        @Override
        public void onAbilityStart(Ability ability) {
            setTopActivity(ability);
            if (mConfigCount < 0) {
                ++mConfigCount;
            } else {
                ++mForegroundCount;
            }
        }

        @Override
        public void onAbilityActive(Ability ability) {
            setTopActivity(ability);
            if (mIsBackground) {
                mIsBackground = false;
                postStatus(true);
            }
        }

        @Override
        public void onAbilityInactive(Ability ability) { }

        @Override
        public void onAbilityForeground(Ability ability) { }

        @Override
        public void onAbilityBackground(Ability ability) {
            if (ability.isUpdatingConfigurations()) {
                --mConfigCount;
            } else {
                --mForegroundCount;
                if (mForegroundCount <= 0) {
                    mIsBackground = true;
                    postStatus(false);
                }
            }
        }

        @Override
        public void onAbilityStop(Ability ability) {
            mActivityList.remove(ability);
            consumeOnActivityDestroyedListener(ability);
            fixSoftInputLeaks(ability);
        }

        @Override
        public void onAbilitySaveState(PacMap pacMap) { }
    }

    public interface OnAppStatusChangedListener {
        void onForeground();

        void onBackground();
    }

    public interface OnActivityDestroyedListener {
        void onActivityDestroyed(Ability activity);
    }
}
